//
//  Controller20.swift
//  Swift30Days
//
//  Created by licheng ke on 2017/3/14.
//  Copyright © 2017年 licheng ke. All rights reserved.
//

import UIKit

// CollectionViewAnimation
class Controller20 : UIViewController,
                     UICollectionViewDataSource,
                     UICollectionViewDelegate
{

    var collectionView : UICollectionView!
    
    let datas = Travel.fakeDatas()
    var tmpRect : CGRect?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor(white: 0.7, alpha: 0.5)
        configUI();
    }

    func configUI(){
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: SCREEN_W , height: SCREEN_W * 0.8)
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .vertical
        
        collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UINib(nibName: "CustomCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "abc")
        view.addSubview(collectionView)
        
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return datas.count;
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "abc", for: indexPath) as! CustomCollectionViewCell
        cell.callBack = self.handleCellBack
        cell.travel = datas[indexPath.row]
        cell.pressCellConfigCell();
        cell.setNeedsLayout();
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as! CustomCollectionViewCell
        UIView.animate(withDuration: 0.5, animations: {
            self.tmpRect = cell.frame
            var frame = collectionView.bounds
            print("\(frame)")
            frame.origin.y += 64
            frame.size.height -= 64
            cell.frame = frame;
            cell.superview?.bringSubview(toFront: cell)
            cell.sketchCellConfig()
        }) { (flag) in
            collectionView.isScrollEnabled = false
        }
    }
    
    func handleCellBack(cell:UICollectionViewCell){
        UIView.animate(withDuration: 0.5, animations: {
            cell.frame = self.tmpRect!
        }) { (flag) in
            self.collectionView.reloadItems(at: self.collectionView.indexPathsForSelectedItems!)
            self.collectionView.isScrollEnabled = true
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    


}
